package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.GiftDetailsDto;
import com.huaxiafinance.management.dto.request.QueryGiftDto;
import com.huaxiafinance.management.dto.request.ScoreGiftDto;
import com.huaxiafinance.management.mapper.ScoreGiftCodeMapper;
import com.huaxiafinance.management.mapper.ScoreGiftMapper;
import com.huaxiafinance.management.mapper.YfqDictionaryMapper;
import com.huaxiafinance.management.model.ScoreGift;
import com.huaxiafinance.management.model.ScoreGiftCode;
import com.huaxiafinance.management.service.ScoreGiftService;
import com.huaxiafinance.management.util.DateUtil;
import com.huaxiafinance.management.util.ExportExcelUtil;
import com.huaxiafinance.management.util.GiftCodeUtil;
import com.huaxiafinance.management.util.MessageResult;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by huangwencheng on 2017/11/09.
 */
@Service("ScoreGiftService")
@SuppressWarnings("SpringJavaAutowiringInspection")
@Transactional
public class ScoreGiftServiceImpl implements ScoreGiftService {

    private static final Logger log = Logger.getLogger(ScoreGiftServiceImpl.class);

    @Autowired
    private ScoreGiftMapper scoreGiftMapper;

    @Autowired
    private ScoreGiftCodeMapper scoreGiftCodeMapper;

    @Autowired
    private YfqDictionaryMapper yfqDictionaryMapper;

    /**
     * 请求兑换码列表
     *
     * @return
     */
    @Override
    public MessageResult queryScoreGiftList(QueryGiftDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        List<ScoreGift> scoreGiftList = null;
        int scoreGiftSum = 0;
        if (dto.getStartTime() != null && dto.getEndTime() != null &&
                !("").equals(dto.getStartTime()) &&
                !("").equals(dto.getEndTime())) {
            Map<String, Date> map = DateUtil.getTimeFormat(dto.getStartTime(), dto.getEndTime());
            dto.setStartDate(map.get("beginTime"));
            dto.setEndDate(map.get("overTime"));
        } else {
            dto.setStartTime(null);
            dto.setEndTime(null);
        }
        dto.setNowDate(new Date());
        dto.setPage(dto.getPage() * dto.getRows());
        //查询列表
        scoreGiftList = scoreGiftMapper.queryScoreGifts(dto);
        //统计数量
        scoreGiftSum = scoreGiftMapper.countScoreGift(dto);
        messageResult.setData(scoreGiftList);
        messageResult.setRows(scoreGiftSum);
        messageResult.setSuccessResult();
        return messageResult;
    }
    
    /**
     * 新增积分礼品
     *
     * @param dto 请求参数
     * @return
     */
    @Override
    public MessageResult insertScoreGift(ScoreGiftDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
            synchronized (this) {
                //判断批次名字是否相同
                ScoreGift scoreGift = scoreGiftMapper.selectByCodeName(dto.getCodeName());
                if (scoreGift == null) {
                    scoreGift = new ScoreGift();
                    scoreGift.setAdminId(dto.getAdminId());
                    scoreGift.setScore(dto.getScore());
                    scoreGift.setCirculation(dto.getCirculation());
                    scoreGift.setRemarks(dto.getRemarks());
                    scoreGift.setAdminId(dto.getAdminId());
                    scoreGift.setGmtCreate(new Date());
                    scoreGift.setGmtModify(new Date());
                    scoreGift.setCodeName(dto.getCodeName());
                    //默认类型为: 1-积分类型
                    scoreGift.setCodeType(1);
                    //兑换量默认为0
                    scoreGift.setExchangeSum(0);
                    scoreGift.setIsPermanent(dto.getIsPermanent());
                    //判断积分礼品是否长久有效 1：长久有效；0：有效期
                    if (dto.getIsPermanent() == 0) {
                        if (StringUtils.isNotBlank(dto.getEndTime())) {
                            scoreGift.setStartTime(new Date());
                            scoreGift.setEndTime(DateUtil.getEndTime(dto.getEndTime()));
                        } else {
                            messageResult.setFailureResult("有效期时间不能为空");
                            return messageResult;
                        }
                    }
                    scoreGiftMapper.insertSelective(scoreGift);
                    scoreGift = scoreGiftMapper.selectByCodeName(dto.getCodeName());
                    Integer scoreGiftId = scoreGift.getId();
                    for (int i = 0; i < dto.getCirculation(); i++) {
                        ScoreGiftCode scoreGiftCode = new ScoreGiftCode();
                        //兑换都为:2-未兑换
                        scoreGiftCode.setIsEffective(2);
                        scoreGiftCode.setScoreGiftId(scoreGiftId);
                        scoreGiftCode.setGmtCreate(new Date());
                        scoreGiftCode.setGmtModify(new Date());
                        String giftCode = null;
                        do {
                            giftCode = GiftCodeUtil.genRandomNum();
                        } while (scoreGiftCodeMapper.selectByPrimaryKey(giftCode) != null);
                        scoreGiftCode.setGiftCode(giftCode);
                        scoreGiftCodeMapper.insertSelective(scoreGiftCode);
                    }
                }else {
                    messageResult.setFailureResult("批次名称不可重复");
                    return messageResult;
                }
            }
            messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 查询兑换批次详情
     *
     * @param id 批次id
     * @return 批次详情
     * @throws Exception
     */
    @Override
    public MessageResult queryScoreGift(Integer id) throws Exception {
        MessageResult messageResult = new MessageResult();
        ScoreGift scoreGift = scoreGiftMapper.selectByPrimaryKey(id);
        messageResult.setData(scoreGift);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 查看积分礼品详情以及兑换码列表
     *
     * @return
     */
    @Override
    public MessageResult queryScoreGiftCode(GiftDetailsDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();
        ScoreGift scoreGift = scoreGiftMapper.selectById(dto.getId(),new Date());
        dto.setPage(dto.getPage() * dto.getRows());
        dto.setNowDate(new Date());
        List<ScoreGiftCode> scoreGiftCodeList = scoreGiftCodeMapper.queryByScoreGiftId(dto);
        int scoreGiftCodes = scoreGiftCodeMapper.countCodes(dto.getId());
        scoreGift.setScoreGiftCodeList(scoreGiftCodeList);
        messageResult.setData(scoreGift);
        messageResult.setRows(scoreGiftCodes);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 查看积分礼品兑换码详情
     *
     * @return
     */
    @Override
    public MessageResult queryCodeDetails(String giftCode) throws Exception {
        MessageResult messageResult = new MessageResult();
        ScoreGiftCode scoreGiftCode = scoreGiftCodeMapper.selectByGiftCode(giftCode,new Date());
        messageResult.setData(scoreGiftCode);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 查看批次列表
     *
     * @return
     */
    @Override
    public MessageResult queryBatchList() throws Exception {
        MessageResult messageResult = new MessageResult();
        List<Map<String, Object>> map = yfqDictionaryMapper.selectDictList(CommonConstant.BATCH_TYPE);
        messageResult.setData(map);
        messageResult.setSuccessResult();
        return messageResult;
    }

    /**
     * 下载兑换码列表
     *
     * @param id       批次id
     * @param response
     */
    @Override
    public void download(String id, HttpServletResponse response) throws Exception {

        if (StringUtils.isNotBlank(id)){
            Integer giftId = Integer.parseInt(id);
            ScoreGift scoreGift = scoreGiftMapper.selectByPrimaryKey(giftId);
            List<ScoreGiftCode> scoreGiftCodeList = scoreGiftCodeMapper.selectByScoreGiftId(giftId,new Date());

            WritableWorkbook workbook = ExportExcelUtil.getExcel(scoreGift.getCodeName(), response);
            /** **********创建工作表************ */
            WritableSheet sheet = ExportExcelUtil.getExcelSheet("兑换码列表", 0, workbook);

            /** ************设置单元格字体************** */


            WritableCellFormat wcf_center = ExportExcelUtil.getCssCenter();
            WritableCellFormat wcf_left = ExportExcelUtil.getCssNormalAndBorder();

            //兑换码  兑换码状态

            sheet.setColumnView(0, 18);
            sheet.setColumnView(1, 18);
            sheet.addCell(new Label(0, 0, "兑换码", wcf_center));
            sheet.addCell(new Label(1, 0, "兑换码的状态", wcf_center));


            int i = 1;
            for (ScoreGiftCode scoreGiftCode : scoreGiftCodeList) {

                sheet.addCell(new Label(0, i, scoreGiftCode.getGiftCode() == null ? "" : scoreGiftCode.getGiftCode(), wcf_left));
                sheet.addCell(new Label(1, i, scoreGiftCode.getEffectiveName() == null ? "" : scoreGiftCode.getEffectiveName(), wcf_left));
                i++;
            }

            /** **********将以上缓存中的内容写到EXCEL文件中******** */
            workbook.write();
            /** *********关闭文件************* */
            workbook.close();
        }else {
            log.info("下载出现异常没有传id");
        }

    }

    /**
     * 查看所有兑换码
     *
     * @return
     */
    @Override
    public MessageResult queryAllCode(Integer giftCodeId) throws Exception {
        MessageResult messageResult = new MessageResult();
        List<ScoreGiftCode> scoreGiftCodeList = scoreGiftCodeMapper.selectByScoreGiftId(giftCodeId,new Date());
        messageResult.setData(scoreGiftCodeList);
        messageResult.setSuccessResult();
        return messageResult;
    }

}
